/**
 * 
 */
package dms.presentation.action.sys;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import dms.dto.SystemAdministratorDTO;
import dms.model.role.wrapper.SystemAdministratorWrapper;
import dms.service.AuthenticationService;
import dms.util.Constant;
import dms.util.ContextUtil;

/**
 * @author 李健
 *
 */
public class AddSystemAdministratorAction extends Action {
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		ActionErrors errors = new ActionErrors();
		SystemAdministratorDTO systemAdministratorDTO = (SystemAdministratorDTO) form;
		
		String password = systemAdministratorDTO.getPassword();
		String oldPassword = systemAdministratorDTO.getOldPassword();
		String name = systemAdministratorDTO.getName();
		String email = systemAdministratorDTO.getEmail();
		
		if (name == null || name.length() == 0) {
			errors.add("errors", new ActionMessage("用户名为空", false));
			this.addErrors(request, errors);
			return mapping.getInputForward();
		}
		if (password == null || password.length() == 0) {
			errors.add("errors", new ActionMessage("密码为空", false));
			this.addErrors(request, errors);
			return mapping.getInputForward();
		}
		if (oldPassword == null || oldPassword.length() == 0) {
			errors.add("errors", new ActionMessage("密码为空", false));
			this.addErrors(request, errors);
			return mapping.getInputForward();
		}
		if (email == null || email.length() == 0) {
			errors.add("errors", new ActionMessage("电子邮件为空", false));
			this.addErrors(request, errors);
			return mapping.getInputForward();
		}
		if (!password.equals(oldPassword)) {
			errors.add("errors", new ActionMessage("前后密码输入错误", false));
			this.addErrors(request, errors);
			return mapping.getInputForward();
		}
		
		AuthenticationService authenticationService = (AuthenticationService) ContextUtil.getContext().getBean("authenticationService");
		boolean exist = authenticationService.isUserExist(name);
		if (exist) {
			ActionMessage msg = new ActionMessage("该用户名已存在", false);
			errors.add("errors", msg);
			this.addErrors(request, errors);
			return mapping.getInputForward();
			
		}
		
		SystemAdministratorWrapper saWrapper = (SystemAdministratorWrapper) ContextUtil.getContext().getBean("systemAdministratorWrapper");
		saWrapper.addSystemAdministrator(systemAdministratorDTO);
		
		return mapping.findForward(Constant.SUCCESS);
	}
}
